import Flutter
import UIKit
import StoreKitSDK
public class FlutterPluginStorekitPlugin: NSObject, FlutterPlugin {
    // 保存订阅通道引用
    static var subscribeChannel: FlutterMethodChannel?
    public static func register(with registrar: FlutterPluginRegistrar) {
        subscribeChannel = FlutterMethodChannel(name: "com.cqxm.app/SubscribeChannel", binaryMessenger: registrar.messenger())
        let instance = FlutterPluginStorekitPlugin()
        registrar.addMethodCallDelegate(instance, channel: subscribeChannel!)
    }
    
    //订阅通道
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "getSubscriptionProductList":
            //获取订阅产品列表
            // 从call.arguments中提取参数
            guard let args = call.arguments as? [String: Any] else {
                result(FlutterError(code: "INVALID_ARGS",
                                    message: "参数格式错误",
                                    details: nil))
                return
            }
            
            // 提取必须的参数
            guard let productIds = args["productIds"] as? [String],
                  let language  = args["language"] as? String else {
                result(FlutterError(code: "MISSING_PARAMS",
                                    message: "缺少必要参数",
                                    details: nil))
                return
            }
            
            // 提取可选参数
            let ssDistinctId = args["ssDistinctId"] as? String
            let ssAccountId = args["ssAccountId"] as? String
            let baseURL = args["baseURL"] as? String
            let checkOrder = args["checkOrder"] as? String
            let report = args["report"] as? String
            let retryTime = args["retryTime"] as? Double
            
            // 调用您的StoreKit方法
            self.getSubscriptionProductList(
                productIds: productIds,
                ssAccountId: ssAccountId,
                ssDistinctId: ssDistinctId,
                language: language,
                baseURL: baseURL,
                checkOrder: checkOrder,
                report: report,
                retryTime: retryTime
            ) { products in
                // 返回结果到Flutter
                result(products)
            }
        case "purchaseSubscription":
            //购买订阅
            guard let args = call.arguments as? [String: Any] else {
                result(FlutterError(code: "INVALID_ARGS",
                                    message: "参数格式错误",
                                    details: nil))
                return
            }
            // 提取必须的参数
            guard let productId = args["productId"] as? String,
                  let reportDic = args["reportDic"] as? [String: Any] else {
                result(FlutterError(code: "MISSING_PARAMS",
                                    message: "缺少必要参数",
                                    details: nil))
                return
            }
            self.purchaseSubscription(productId, reportDic){res, message in
                // 返回结果到Flutter
                result([res, message])
            }
        case "restoreSubscribe":
            //恢复订阅
            self.restorePurchasesTapped { res, message in
                result([res, message])
            }
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    
    
    //获取订阅产品
    func getSubscriptionProductList(
        productIds: [String],
        ssAccountId: String?,
        ssDistinctId: String?,
        language: String,
        baseURL: String?,
        checkOrder: String?,
        report: String?,
        retryTime: Double?,
        completion: @escaping ([[String: Any]]) -> Void
    ){
        // 配置参数
        let storeKitConfig = StoreKitConfiguration(
            productIds: productIds,
            ssAccountId: ssAccountId,
            ssDistinctId: ssDistinctId,
            language: language,
            baseURL: baseURL,
            checkOrder: checkOrder,
            report: report,
            retryTime: retryTime,
        )
        
        StoreKitManager.configure(with: storeKitConfig);
        StoreKitManager.shared.productsCallback = { [weak self] products in
            print(products);
            // 转换每个产品为 Flutter 可用格式
            let flutterProducts = products.map { product in
                return product.toFlutterMap()
            }
            // 1. 向Flutter发送数据
            self?.sendProductsToFlutter(flutterProducts)
            // 返回结果到原始调用
            completion(flutterProducts)
            
        }
        
        //订单验证，如果有订阅会回调
        StoreKitManager.shared.orderCallback = { [weak self] isSubscribed, curretProduct, reportRequestData, orderData in
            self?.sendSubscribedToFlutter(isSubscribed: isSubscribed, product: curretProduct.toFlutterMap(), reportRequestData: reportRequestData.toFlutterMap(), orderData: orderData.toFlutterMap())
        }
        
        //没有订阅会回掉
        StoreKitManager.shared.noOrderCallback = { [weak self] in
            //没有订阅会回掉
            self?.sendNOSubscribedToFlutter()
        }
        
        //获取历史订单回掉
        StoreKitManager.shared.historyTransactionCallback = { [weak self] historyTransaction in
            // 转换每个产品为 Flutter 可用格式
            let flutterHistoryTransaction = historyTransaction.map { transaction in
                return transaction.toFlutterMap()
            }
            //获取历史订单回掉
            self?.sendHistoryTransactionToFlutter(flutterHistoryTransaction);
        }
    }
    
    // 向Flutter发送产品数据
    func sendProductsToFlutter(_ products: [[String: Any]]) {
        // 确保在主线程调用Flutter方法
        DispatchQueue.main.async {
            FlutterPluginStorekitPlugin.subscribeChannel?.invokeMethod(
                "onProductsReceived",
                arguments: ["products": products]
            )
        }
    }
    
    //向Flutter发送历史订单
    func sendHistoryTransactionToFlutter(_ historyTransaction: [Any]) {
        // 确保在主线程调用Flutter方法
        DispatchQueue.main.async {
            FlutterPluginStorekitPlugin.subscribeChannel?.invokeMethod(
                "getSubscriptionHistoryOrder",
                arguments: ["historyTransaction": historyTransaction]
            )
        }
    }
    
    // 向Flutter发送订阅数据
    func sendSubscribedToFlutter(isSubscribed: Bool, product: [String: Any], reportRequestData: [String: Any], orderData: [String: Any]) {
        // 确保在主线程调用Flutter方法
        DispatchQueue.main.async {
            FlutterPluginStorekitPlugin.subscribeChannel?.invokeMethod(
                "onSubscribedReceived",
                arguments: ["isSubscribed": isSubscribed, "product": product, "reportRequestData": reportRequestData, "orderData": orderData]
            )
        }
    }
    
    // 向Flutter发送没有订阅数据
    func sendNOSubscribedToFlutter() {
        // 确保在主线程调用Flutter方法
        DispatchQueue.main.async {
            FlutterPluginStorekitPlugin.subscribeChannel?.invokeMethod(
                "noSubscription", arguments: nil
            )
        }
    }
    
    //开始订阅
    private func purchaseSubscription(_ productId: String, _ reportDic: [String: Any], completion: @escaping (Bool, String) -> Void) {
        guard let product:ProductData = StoreKitManager.shared.allProducts.filter({ $0.productIdentifier == productId }).first else{
            return completion(false, "-1:未找到产品");
        }
        //更新数数的账号和访客ID
        StoreKitManager.shared.configuration.ssAccountId = reportDic["ss_account_id"] as? String;
        StoreKitManager.shared.configuration.ssDistinctId = reportDic["ss_distinct_id"] as? String;
        StoreKitManager.shared.purchaseSubscription(product) { [weak self] success, res, error in
            //            print(res ?? "");
            //            if let myRes = res {
            //                switch myRes {
            //                case .success(let response):
            //                    let isExpired = response.is_expired;
            //                    print("是否过期：\(String(describing: isExpired))");
            //                case .failure(let error):
            //                    print("是否过期：\(error)");
            //                }
            //            }
            
            if(success){
                //                //判断是否是免费订单，免费订单不上报
                //                if StoreKitManager.shared.reportRequestData?.isFreeSubscription == true{
                //                    completion(true, "订阅成功，免费订单不上报");
                //                    return;
                //                }
                
                //订阅成功调用上报接口
                self?.reportIap(user_id: reportDic["user_id"] as! String, ua: reportDic["ua"] as? String, idfa: reportDic["idfa"] as! String, idfv: reportDic["idfv"] as! String, adid: reportDic["adid"] as! String, ad_network: reportDic["ad_network"] as! String, campaign: reportDic["campaign"] as! String, adgroup: reportDic["adgroup"] as! String, creative: reportDic["creative"] as! String, country: reportDic["country"] as! String, product_type: reportDic["product_type"] as! String, ss_account_id: reportDic["ss_account_id"] as? String, ss_distinct_id: reportDic["ss_distinct_id"] as? String, completion: completion);
            }else{
                //订阅失败
                completion(false, error != nil ? "\(error!.code):\(error?.localizedDescription ?? "")" : "订阅失败:\(error?.localizedDescription ?? "")");
            }
            
        }
    }
    
    //恢复订阅
    private func restorePurchasesTapped(completion: @escaping (Bool, String) -> Void) {
        StoreKitManager.shared.restorePurchases {success, res, error in
            //            print(res ?? "");
            //            if let myRes = res {
            //                switch myRes {
            //                case .success(let response):
            //                    let isExpired = response.is_expired;
            //                    print("是否过期：\(String(describing: isExpired))");
            //                case .failure(let error):
            //                    print("是否过期：\(error)");
            //                }
            //            }
            if(success){
                completion(true, "恢复订阅成功");
            }else{
                //订阅失败
                completion(false, "订阅失败:\(error?.localizedDescription ?? "")");
            }
            
        }
    }
    
    //上报
    private func reportIap(
        user_id: String, //登录用户ID，默认为空
        user_type: Int = 0, //用户类型: 用户类型: 游客：0，邮箱：1, Google：2, facebook：3, apple：4
        ua: String?,//用户代理，是一个特殊字符串头，能够识别客户使用的操作系统及版本、CPU 类型、浏览器及版本、浏览器渲染引擎、浏览器语言等
        idfa: String,//原始 IDFA (仅限 iOS)
        idfv: String, //原始 IDFV (仅限 iOS)
        adid: String,//Adjust 设备 ID
        ad_network: String, //上报Adjust回传的ad_network的对应信息
        campaign: String,//上报Adjust回传的campaign的对应信息
        adgroup: String, //上报Adjust回传的adgroup的对应信息
        creative: String,//上报Adjust回传的creative的对应信息
        country: String,//可以根据adjust给到的国家两位代码，例如US
        product_type: String,
        ss_account_id: String?,//数数接入的账号id,用户的登录ID(如果需要接入数数请务必传此值)
        ss_distinct_id: String?,//数数接入的访客id,用户在未登录状态下的ID(如果需要接入数数请务必传此值)
        //language: String?,//语言
        unverified_order: Int = 0, //是否验证订单,0:默认验证，1：不验证，如果已经调用过iap支付订单验证接口，此字段设置为1不验证即可，如果没有使用iap订单验证接口，建议采用0进行服务端验证
        completion: @escaping (Bool, String) -> Void
    ){
        guard let reportRequestData = StoreKitManager.shared.reportRequestData else {
            completion(true, "订阅成功，没有需要的产品信息上报失败");
            return
        }
        
        StoreKitManager.reportIap(user_id: user_id, user_type:user_type, ua:ua ?? ((URLSession.shared.configuration.httpAdditionalHeaders?["User-Agent"] as? String) ?? ""), idfa: idfa, idfv: idfv, adid: adid, ad_network: ad_network, campaign: campaign, adgroup: adgroup, creative: creative, transactionId: reportRequestData.transactionId, productId: reportRequestData.productId, currency: reportRequestData.currency, price: reportRequestData.price, country: country, iap_name: reportRequestData.productId, product_type: product_type, ss_account_id: ss_account_id, ss_distinct_id: ss_distinct_id, language: StoreKitManager.shared.configuration.language, unverified_order:unverified_order){ (result: ApiResult<ReportResponse>) in
            switch result {
            case .success(let response):
                // 处理成功响应
                print("上报成功: \(response)")
                completion(true, "订阅后上报成功");
                break;
            case .failure(let error):
                // 处理错误响应
                print("上报失败: \(error.localizedDescription)")
                completion(true, "\(error.code):\(error.localizedDescription)");
                break;
            }
        }
    }
}
